package com.dmlll.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmlll.VO.PurchaseDrugDetailVO;
import com.dmlll.VO.PurchaseVO;
import com.dmlll.common.DataGridView;
import com.dmlll.common.ResultObj;
import com.dmlll.domain.*;
import com.dmlll.mapper.HospitalMapper;
import com.dmlll.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dmLll
 * @since 2021-03-31
 */
@RestController
@RequestMapping("/purchase")
public class PurchaseController {
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private PurchaseDrupDetailService purchaseDrupDetailService;
    @Autowired
    private DrugMessageService drugMessageService;
    @Autowired
    private DrugCategoryService drugCategoryService;
    @Autowired
    private SuperviseService superviseService;
    @Autowired
    private AreaService areaService;

    @RequestMapping("/loadAllPurchase")
    public DataGridView loadAllPurchase(PurchaseVO purchaseVO) {
        IPage<Purchase> iPage = new Page<>(purchaseVO.getPage(), purchaseVO.getLimit());
        if (purchaseVO.getHospitalId() != null) {
            QueryWrapper<Purchase> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("hospital_id", purchaseVO.getHospitalId());
            queryWrapper.like(StringUtils.isNotBlank(purchaseVO.getPurchaseNum()), "purchase_num", purchaseVO.getPurchaseNum());
            queryWrapper.like(StringUtils.isNotBlank(purchaseVO.getPurchaseName()), "purchase_name", purchaseVO.getPurchaseName());
            queryWrapper.eq(purchaseVO.getPurchaseState() != null && purchaseVO.getPurchaseState() != 0, "purchase_state", purchaseVO.getPurchaseState());
            queryWrapper.le(purchaseVO.getEndTime() != null, "create_time", purchaseVO.getEndTime());
            queryWrapper.ge(purchaseVO.getStartTime() != null, "create_time", purchaseVO.getStartTime());
            queryWrapper.orderByDesc("create_time");
            purchaseService.page(iPage, queryWrapper);
        }
        for (Purchase purchase : iPage.getRecords()) {
            purchase.setHospitalName(hospitalService.getById(purchase.getHospitalId()).getHospitalName());
        }
        return new DataGridView(iPage.getTotal(), iPage.getRecords());
    }

    @SuppressWarnings("all")
    @RequestMapping("/loadAllPurchase2")
    public DataGridView loadAllPurchase2(HttpSession session, PurchaseVO purchaseVO) {
        User user = (User) session.getAttribute("user");
        if(user==null){
            return new DataGridView();
        }
        Integer type = user.getType();
        Integer unitId = user.getUnitId();
        if (type == 2) {
            Supervise supervise = superviseService.getById(unitId);
            Area areaSupervise = areaService.getById(supervise.getPid());//管辖区域
            IPage<Purchase> iPage = new Page<>(purchaseVO.getPage(), purchaseVO.getLimit());
            QueryWrapper<Purchase> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(purchaseVO.getHospitalId()!=null&&purchaseVO.getHospitalId()>0,"hospital_id", purchaseVO.getHospitalId());
            queryWrapper.like(StringUtils.isNotBlank(purchaseVO.getPurchaseNum()), "purchase_num", purchaseVO.getPurchaseNum());
            queryWrapper.like(StringUtils.isNotBlank(purchaseVO.getPurchaseName()), "purchase_name", purchaseVO.getPurchaseName());
            queryWrapper.eq(purchaseVO.getPurchaseState() != null && purchaseVO.getPurchaseState() != 0, "purchase_state", purchaseVO.getPurchaseState());
            queryWrapper.le(purchaseVO.getEndTime() != null, "create_time", purchaseVO.getEndTime());
            queryWrapper.ge(purchaseVO.getStartTime() != null, "create_time", purchaseVO.getStartTime());
            queryWrapper.orderByDesc("create_time");
            purchaseService.page(iPage, queryWrapper);//所有采购单
            for (Purchase purchase : iPage.getRecords()) {
                Hospital hospital = hospitalService.getById(purchase.getHospitalId());
                Area area = areaService.getById(hospital.getAreaid());//采购单所在医院区域
                if (area.getId() == areaSupervise.getId()) {
                    purchase.setHospitalName(hospitalService.getById(purchase.getHospitalId()).getHospitalName());
                } else {
                    iPage.getRecords().remove(purchase);
                }
            }
            return new DataGridView(iPage.getTotal(), iPage.getRecords());
        } else if (type == 1) {
            Supervise supervise = superviseService.getById(unitId);
            Area areaSupervise = areaService.getById(supervise.getPid());//管辖区域
            IPage<Purchase> iPage = new Page<>(purchaseVO.getPage(), purchaseVO.getLimit());
            List<Area> areaList = areaService.list(new QueryWrapper<Area>().eq("id", areaSupervise.getPid()));
            areaList.add(areaSupervise);//管理的所有区域
            if (purchaseVO.getHospitalId() != null) {
                QueryWrapper<Purchase> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("hospital_id", purchaseVO.getHospitalId());
                queryWrapper.like(StringUtils.isNotBlank(purchaseVO.getPurchaseNum()), "purchase_num", purchaseVO.getPurchaseNum());
                queryWrapper.like(StringUtils.isNotBlank(purchaseVO.getPurchaseName()), "purchase_name", purchaseVO.getPurchaseName());
                queryWrapper.eq(purchaseVO.getPurchaseState() != null && purchaseVO.getPurchaseState() != 0, "purchase_state", purchaseVO.getPurchaseState());
                queryWrapper.le(purchaseVO.getEndTime() != null, "create_time", purchaseVO.getEndTime());
                queryWrapper.ge(purchaseVO.getStartTime() != null, "create_time", purchaseVO.getStartTime());
                queryWrapper.orderByDesc("create_time");
                purchaseService.page(iPage, queryWrapper);//所有采购单
            }
            for (Purchase purchase : iPage.getRecords()) {
                Hospital hospital = hospitalService.getById(purchase.getHospitalId());
                Area area = areaService.getById(hospital.getAreaid());//采购单所在医院区域
                int a = 0;
                for (int i = 0; i < areaList.size(); i++) {
                    if (areaList.get(i).getId() == area.getId()) {
                        a = 1;
                    }
                }//该采购单所在医院在这个范围
                if (a == 1) {
                    a = 0;
                    purchase.setHospitalName(hospitalService.getById(purchase.getHospitalId()).getHospitalName());
                } else {
                    iPage.getRecords().remove(purchase);
                }
            }
            return new DataGridView(iPage.getTotal(), iPage.getRecords());//TODO 测试
        }

        return new DataGridView();
    }

    @RequestMapping("add")
    public ResultObj add(Purchase purchase) {
        purchase.setRecentTime(new Date());
        //设置购物单编号
        Calendar calendar = Calendar.getInstance();
        String purchaseNum = calendar.get(Calendar.YEAR) + UUID.randomUUID().toString().substring(0, 6);
        purchase.setPurchaseNum(purchaseNum);
        try {
            purchaseService.save(purchase);
        } catch (Exception e) {
            return ResultObj.ADD_ERROR;
        }
        return ResultObj.ADD_SUCCESS;
    }

    @RequestMapping("update")
    public ResultObj update(Purchase purchase) {
        try {
            purchaseService.updateById(purchase);
        } catch (Exception e) {
            return ResultObj.UPDATE_ERROR;
        }
        return ResultObj.UPDATE_SUCCESS;
    }

    @RequestMapping("delete")
    public ResultObj delete(Purchase purchase) {
        try {
            purchaseService.removeById(purchase.getId());
        } catch (Exception e) {
            return ResultObj.DELETE_ERROR;
        }
        return ResultObj.DELETE_SUCCESS;
    }

    /**
     * 获得最新的id
     *
     * @return
     */
    @RequestMapping("getNewPurchaseId")
    public Integer getNewPurchaseId() {
        return purchaseService.getNewPurchaseId();
    }

    @RequestMapping("getPurchaseById")
    public Purchase getPurchaseById(Integer id) {
        Purchase purchase = purchaseService.getById(id);
        if (purchase.getHospitalId() != null) {
            Hospital hospital = hospitalService.getById(purchase.getHospitalId());
            purchase.setHospitalName(hospital.getHospitalName());
        }
        return purchase;
    }

    /**
     * 获得该采购单已选择的药品
     *
     * @param purchaseDrugDetailVO 含有采购单id
     * @return
     */
    @RequestMapping("getAvailableDrug")
    public DataGridView getAvailableDrug(PurchaseDrugDetailVO purchaseDrugDetailVO, DrugMessage drugMessage) {
        IPage<DrugMessage> iPage = new Page<>(purchaseDrugDetailVO.getPage(), purchaseDrugDetailVO.getLimit());
        //查出所有筛选的药品信息
        QueryWrapper<DrugMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(drugMessage.getSerialNumber()), "serial_number", drugMessage.getSerialNumber());
        queryWrapper.like(StringUtils.isNotBlank(drugMessage.getCommonName()), "common_name", drugMessage.getCommonName());
        queryWrapper.like(StringUtils.isNotBlank(drugMessage.getDosageForm()), "dosage_form", drugMessage.getDosageForm());
        queryWrapper.like(StringUtils.isNotBlank(drugMessage.getSize()), "size", drugMessage.getSize());
        queryWrapper.like(StringUtils.isNotBlank(drugMessage.getUnit()), "unit", drugMessage.getUnit());
        queryWrapper.like(StringUtils.isNotBlank(drugMessage.getCommodityName()), "commodity_name", drugMessage.getCommodityName());
        queryWrapper.like(StringUtils.isNotBlank(drugMessage.getProductionName()), "production_name", drugMessage.getProductionName());
        queryWrapper.eq(drugMessage.getFactor() != null && drugMessage.getFactor() > 0, "factor", drugMessage.getFactor());
        queryWrapper.eq(drugMessage.getQuality() != null && drugMessage.getQuality() > 0, "quality", drugMessage.getQuality());
        queryWrapper.eq(drugMessage.getDrugCategory() != null && drugMessage.getDrugCategory() > 0, "drug_category", drugMessage.getDrugCategory());
        List<DrugMessage> drugMessages = drugMessageService.list(queryWrapper);
        //获得供应单的所有供应药品细节及对应药品
        List<PurchaseDrupDetail> list = purchaseDrupDetailService.getDetailAndDrug(purchaseDrugDetailVO.getPurchaseId());
        //在根据供应单查询得列表中存在，在模糊查询的药品中也存在，
        //如果供应商id存在
        List<PurchaseDrupDetail> purchaseDrupDetails = new ArrayList<>();
        //药品信息模糊,取交集
        for (PurchaseDrupDetail drupDetail : list) {
            for (DrugMessage dm : drugMessages) {
                if (drupDetail.getDrugMessageId() == dm.getId()) {
                    drupDetail.setDrugMessage(dm);
                    purchaseDrupDetails.add(drupDetail);
                    break;
                }
            }
        }
        if (purchaseDrugDetailVO.getProviderId() != null && purchaseDrugDetailVO.getProviderId() > 0) {
            //留下对应的供应商
            for (int i = 0; i < purchaseDrupDetails.size(); i++) {
                if (purchaseDrupDetails.get(i).getProviderId() != purchaseDrugDetailVO.getProviderId()) {
                    purchaseDrupDetails.remove(purchaseDrupDetails.get(i--));
                }
            }
        }
        if (purchaseDrugDetailVO.getPurchaseState() != null && purchaseDrugDetailVO.getPurchaseState() > 0) {
            //留下对应的采购状态
            for (int i = 0; i < purchaseDrupDetails.size(); i++) {
                if (purchaseDrupDetails.get(i).getPurchaseState() != purchaseDrugDetailVO.getPurchaseState()) {
                    purchaseDrupDetails.remove(purchaseDrupDetails.get(i--));
                }
            }
        }
        return new DataGridView(iPage.getTotal(), purchaseDrupDetails);
    }

    /**
     * 导出勾选的药品信息
     */
    @RequestMapping("outputDrugMessage")
    public void outputDrugMessage(PurchaseDrupDetail[] purchaseDrupDetails) {
        //未经后台
    }
}

